<?php

namespace app\admin\controller\shop\market\coupon;

use app\admin\controller\shop\Base;
use app\shop\enums\coupon\CouponDiscountType;
use app\shop\enums\coupon\CouponRangeType;
use think\db\exception\DbException;
use Throwable;

/**
 * 优惠券列管理
 */
class Coupon extends Base
{
    /**
     * Coupon模型对象
     * @var object
     * @phpstan-var \app\admin\model\shop\market\coupon\Coupon
     */
    protected object $model;

    protected string|array $defaultSortField = 'weigh,desc';

    protected array|string $preExcludeFields = ['id', 'create_time', 'update_time', 'delete_time'];

    protected string|array $quickSearchField = ['name'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\shop\market\coupon\Coupon;
    }


    /**
     * 若需重写查看、编辑、删除等方法，请复制 @see \app\admin\library\traits\Backend 中对应的方法至此进行重写
     */

    /**
     * 远程搜索
     * @return void
     * @throws Throwable
     * @throws DbException
     */
    public function select(): void
    {
        $rangeType = CouponRangeType::getAllDescriptions();

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit)
            ->each(function ($item) use ($rangeType) {
                $item['discount_desc'] = match ($item['discount_type']) {
                    CouponDiscountType::DISCOUNT_AMOUNT => $rangeType[$item['range_type']] . ',满' . $item['min_price'] . '减' . $item['discount_amount'] . '元',
                    CouponDiscountType::DISCOUNT_RATIO => $rangeType[$item['range_type']] . ',满' . $item['min_price'] . '打' . ($item['discount_ratio']) . '折'
                };
            });

        $this->success('', [
            'list'  => $res->items(),
            'total' => $res->total(),
        ]);
    }
}